#include "SFMLContext.h"
#include "Base/StateManager.h"
#include "Base/Logger.h"
#include "Base/Exceptions.h"
#include <boost/lexical_cast.hpp>
#include <iostream>


SFMLContext::SFMLContext() : Context()
{
    mpt_stateManager->setParent(this);
	mpv_app = new sf::RenderWindow;
	Assert(mpv_app!=NULL);
    mpv_app->create(sf::VideoMode(800, 600, 32), "RageKill");
    mpt_input = boost::shared_ptr<EventObservable>(new EventObservable());
	mpv_app->setFramerateLimit(60);
	mpv_app->setVerticalSyncEnabled(false);

	//mpv_app->showMouseCursor(false);
	
}

SFMLContext::~SFMLContext()
{
	mpt_stateManager->popAllStates();
	delete mpv_app;
	BPL::Logger::log("delete SFMLContext");
}

void SFMLContext::launch()
{
	sf::Clock clock;
    while(mpt_run)
    {
        sf::Event Event;
        while(mpv_app->pollEvent(Event))
        {
			if(Event.type == sf::Event::Closed || Event.key.code == sf::Keyboard::Escape)
                quit();
            else if(mpt_input != NULL)
                mpt_input->sendEvent(Event);
        }
		mpt_stateManager->update(clock.restart().asSeconds());
    }
}

void SFMLContext::quit()
{
    mpt_run = false;
    mpv_app->close();
}

